package com.example.text.diyviews;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.text.R;

public class MyView extends View {
    private Paint mPaint; //构造中创建画笔，千万不要在onDraw，否则产生内存抖动
    private int mColor;//颜色
    private int mRadius;//半径
    public MyView(Context context) {
        this(context,null);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr,0);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.MyView);
        mColor=typedArray.getColor(R.styleable.MyView_color, Color.BLUE);
        mRadius=typedArray.getInt(R.styleable.MyView_radius,0);
        //这里的颜色，半径给的都是默认的一个，真正的在使用布局的时候会传进来
        initPaint();
    }

    private void initPaint() {
        mPaint=new Paint();
        mPaint.setAntiAlias(true);//抗锯齿
        mPaint.setDither(true);//防抖动
        mPaint.setColor(mColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width_mode = MeasureSpec.getMode(widthMeasureSpec);
        int width_size = MeasureSpec.getSize(widthMeasureSpec);
        Log.d("MyViewGroup", "宽度测量模式: "+width_mode);
        Log.d("MyViewGroup", "宽度测量大小: "+width_size);
        int height_mode = MeasureSpec.getMode(heightMeasureSpec);
        int height_size = MeasureSpec.getSize(heightMeasureSpec);
        Log.d("MyViewGroup", "高度测量模式: "+height_mode);
        Log.d("MyViewGroup", "高度测量大小: "+height_size);
        //wrap_content处理
        if ( width_mode == MeasureSpec.AT_MOST){
            width_size = mRadius * 2;
        }
        if (height_mode == MeasureSpec.AT_MOST){
            height_size = mRadius * 2;
        }
        setMeasuredDimension(width_size,height_size);
    }

    /**
     * canvas画布
     * paint画笔
     * @param canvas
     */

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(getMeasuredWidth()/2,getMeasuredHeight()/2,mRadius,mPaint);
    }
}
